package com.company.huisuo.biz.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.view.isVisible
import com.company.huisuo.base.BaseSingleAdapter
import com.company.huisuo.biz.bean.ProductBean
import com.company.huisuo.databinding.ItemCartDataBinding
import com.company.huisuo.ext.loadImg


class CartDataAdapter(private val selectClick: (ProductBean) -> Unit) : BaseSingleAdapter<ProductBean, ItemCartDataBinding>() {
    override val initViewBinding: (LayoutInflater, ViewGroup, Boolean) -> ItemCartDataBinding
        get() = ItemCartDataBinding::inflate

    override fun convert(
        holder: SingleViewHolder<ItemCartDataBinding>, position: Int, item: ProductBean?
    ) {
        holder.binding.apply {
//            ivIcon
            tvName.text = item?.name ?: ""
            tvPrice.text = "¥${(item?.price ?: 0) / 100}" // 价格从分转换为元
            tvNumber.text = "${item?.number ?: 0}"
            tvSales.text= "已售${item?.salesCount ?: 0}"
            tvNumber.isVisible = (item?.number ?: 0) >= 1
            tvReduce.isVisible = (item?.number ?: 0) >= 1
            ivIcon.loadImg(item?.picUrl ?: "")

            tvSelect.setOnClickListener {
                item?.also {
                    selectClick.invoke(it)
                }
            }
            tvAdd.setOnClickListener {
                item?.also {
                    if (it.number < 99) {
                        it.number++
                        notifyItemChanged(position)
                    }
                }
            }
            tvReduce.setOnClickListener {
                item?.also {
                    if (it.number > 0) {
                        it.number--
                        notifyItemChanged(position)
                    }
                }
            }
        }
    }
}